package com.youdianstar.app.common.base

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Process
import android.text.TextUtils
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.view.ContextThemeWrapper
import androidx.core.content.ContextCompat
import androidx.databinding.ViewDataBinding
import com.youdianstar.app.common.R
import com.youdianstar.app.common.PHOTO_ALBUM
import com.youdianstar.app.common.util.*

import com.ss.picker.ImagePicker
import com.ss.picker.ImagePicker.Companion.registerImagePicker
import com.ss.picker.listener.ImagePickerResultListener
import com.ss.picker.model.PickExtension
import com.ss.picker.model.PickerType
import com.ss.picker.util.isAtLeast11

import com.vmadalin.easypermissions.EasyPermissions


/**
 * File: BaseActivity
 * Author: 82149 Create: 2021/9/18 18:23
 * Changes (from 2021/9/18)
 * --------------------------------------------------
 * description: 二次继承 , 补充些常用方法
 * ---------------------------------------------------
 *
 */
abstract class BaseActivity<DB : ViewDataBinding, VM : BaseViewModel> : BaseBMActivity<DB, VM>(),EasyPermissions.PermissionCallbacks {
    abstract override fun layoutId(): Int

    abstract override fun initVariableId(): Int

    override fun attachBaseContext(newBase: Context?) {
        val localLan = LanguageConfig.instance.getLanguageCode()
        if (null!=newBase){
            val mContext = LanguageUtils.createAttachContext(newBase,localLan)
            val configuration = mContext!!.resources.configuration
            val wrappedContext = object : ContextThemeWrapper(mContext, androidx.appcompat.R.style.Theme_AppCompat) {
                override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) {
                    overrideConfiguration?.setTo(configuration)
                    super.applyOverrideConfiguration(overrideConfiguration)
                }
            }
            super.attachBaseContext(wrappedContext)
        } else
            super.attachBaseContext(newBase)
//        super.attachBaseContext(newBase)
    }

    /**
     * 修改本地语言
     * code Language
     */
    private fun setLocalLanguage(){
        val language = LanguageConfig.instance.getLanguageCode()
        LanguageUtils.changeLocalLanguage(this,language)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLocalLanguage()
    }

    override fun initContentCreate() {

    }

    override fun initView(savedInstanceState: Bundle?) {

    }

    override fun initViewLayout() {

    }

    override fun initData() {

    }

    override fun initLiveObserver() {

    }

    /**
     * toast
     *
     * @param text
     */
    fun toastShow(text: String?, type: Int = 0) {
        if (TextUtils.isEmpty(text))
            return
        val prefix = if (type == 1) "AT-" else ""
        ToastUtil.show(this,"$prefix$text")
    }

    //---------------------------------------权限-------------------------------------
    private var permissionCallback :IPermissionActionCallback? = null

    private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
        if (isGranted) {
            permissionCallback?.onPermissionGranted(true,"")
        } else {
            permissionCallback?.onPermissionGranted(false,"")
        }
    }

    fun requestPermission(permission:String, callback:IPermissionActionCallback? =null){
        if (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED) {
            callback?.onPermissionGranted(true,permission)
        }else {
            permissionCallback = callback
            requestPermissionLauncher.launch(permission)
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        //权限允许
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        //权限不允许
    }

    val REQUEST_PERMISSION_CODE = 100

    /**
     * 请求权限-EasyPermissions
     * @param permissions 权限内容 多个
     */
    fun requestPermission(tips :String, vararg permissions: String,code:Int?=null, granted :() -> Unit = {}){
        if (EasyPermissions.hasPermissions(this, *permissions)){
            granted.invoke()
        } else {
            EasyPermissions.requestPermissions(host = this, rationale = tips, requestCode = code?:REQUEST_PERMISSION_CODE, perms = permissions)
        }
    }

    /**
     * 判断权限是否存在
     *
     * @param permissions 权限
     */
    fun isPermissions(vararg permissions: String):Boolean {
        return EasyPermissions.hasPermissions(this, *permissions)
    }

    //------------------------------------------------------------------------------------

    fun requestCameraPermission(grantedCallback :() -> Unit = {}) {
        val requestArray: Array<String> = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arrayOf(Manifest.permission.CAMERA)
        } else {
            arrayOf(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
        }
        requestPermission(getString(R.string.Camera_Permission_Tip),
            *requestArray, granted = grantedCallback)
    }

    fun requestAlbumPermission(grantedCallback :() -> Unit = {}) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
            grantedCallback.invoke()
        }else{
            requestPermission(getString(R.string.Camera_Storage_Permission_Tip),
                Manifest.permission.READ_EXTERNAL_STORAGE, granted = grantedCallback)
        }
    }

    private var imagePicker: ImagePicker? = null

    /**
     * 开启SS选择图片
     *
     * @param type PHOTO_CAMERA/PHOTO_CAMERA
     */
    open fun startSLImagePicker(mContext: Context,
                                type: Int, needCrop : Boolean = true,
                                callback: (String) -> Unit
    ){
        if (null == imagePicker)
            imagePicker = registerImagePicker(object : ImagePickerResultListener {
                override fun onImagePick(uri: Uri?) {
                    uri?.let { u ->
                        try {
                            LogUtil.d("---path ："+u.path)
                            val path: String = FileUtil.compressUriToFile(mContext,u,"${StrUtil.getRandomStr()}.jpg")
                            //val path: String = FileUtil.InputStream2File(mContext, contentResolver.openInputStream(u), "${StrUtil.getRandomStr()}.jpg")
                            callback(path)
                        } catch (e: Exception) {
                            toastShow(e.message)
                        }
                    }
                }

                override fun onMultiImagePick(uris: List<Uri>?) {}
            })
        imagePicker?.let { p->
            p.title(getString(R.string.pick_name))
                .multipleSelection(false, 3)
                .showCountInToolBar(true)
                .showFolder(true)
                .cameraIcon(false) //相册选择支持相机
                .doneIcon(true)
                .allowCropping(needCrop)
                .compressImage(false,80)

                .maxImageSize(4.5f)
                .extension(PickExtension.ALL)
            if (isAtLeast11()) {
                p.systemPicker(true)
            }
            if (type == PHOTO_ALBUM){
                p.open(PickerType.GALLERY)
            }else{
                p.open(PickerType.CAMERA)
            }
        }
    }

    fun killAndRestart(cls: Class<*>){
        val intent = Intent(this, cls)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        startActivity(intent)

        Process.killProcess(Process.myPid())
        System.exit(0)
    }

}